package com.lib.utils;

import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 该类已经适配小米4.4.4系统（miui 7） 小米6.0系统（miui 8）
 */
public class SystemAlertUtils {
    public static final String ACTION_MANAGE_OVERLAY_PERMISSION = "android.settings.action.MANAGE_OVERLAY_PERMISSION";
    private static final int OVERLAY_PERMISSION_REQ_CODE = 0xFF;

    private static final String MIUI_INTENT_ACTION_APP_PERM_EDITOR = "miui.intent.action.APP_PERM_EDITOR";
    private static final String COM_MIUI_SECURITY_CENTER = "com.miui.securitycenter";
    private static final String EXTRA_PACKGE_NAME = "extra_pkgname";
    private static final String COM_MIUI_PERMCENTER_PERMISSIONS_APP_PERMISSIONS_EDITOR_ACTIVITY
            = "com.miui.permcenter.permissions.AppPermissionsEditorActivity";
    private static final String PACKAGE = "package";
    private static final String COM_MIUI_PERMCENTER_PERMISSIONS_PERMISSIONS_EDITOR_ACTIVITY
            = "com.miui.permcenter.permissions.PermissionsEditorActivity";
    private static boolean mIsMiuiSystem;
    private static int mMiuiVersion = -1;

    static {
        mIsMiuiSystem = checkIsMiuiRom();
        if (mIsMiuiSystem) {
            mMiuiVersion = getMiuiVersion();
        }
    }

    public static boolean isMiuiSystem() {

        return mIsMiuiSystem;
    }

    public static int getVersion() {

        return mMiuiVersion;
    }

    /**
     * 获取小米 rom 版本号，获取失败返回 -1
     *
     * @return miui rom version code, if fail , return -1
     */
    private static int getMiuiVersion() {

        String version = getSystemProperty("ro.miui.ui.version.name");
        if (version != null) {
            try {
                return Integer.parseInt(version.substring(1));
            } catch (Exception e) {
                XLog.w("get miui version code error, version : " + version);
            }
        }
        return -1;
    }

    /**
     * check if is miui ROM
     */
    private static boolean checkIsMiuiRom() {
        return !TextUtils.isEmpty(getSystemProperty("ro.miui.ui.version.name"));
    }

    private static String getSystemProperty(String propName) {

        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (Exception ex) {
            XLog.w("Unable to read sysprop " + propName + ex.toString());
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    XLog.w("Exception while closing InputStream" + e);
                }
            }
        }
        return line;
    }

    public static boolean gotoMiuiAlertWindowSystem(Activity activity, int requestCode) {

        if (mMiuiVersion == 5) {
            return goToMiuiPermissionActivity_V5(activity, requestCode);
        } else if (mMiuiVersion == 6 || mMiuiVersion == 7) {
            return goToMiuiPermissionActivity_V6(activity, requestCode);
        } else if (mMiuiVersion == 8) {
            return goToMiuiPermissionActivity_V8(activity, requestCode);
        }
        return false;
    }

    /**
     * 小米 V5 版本 ROM权限申请
     */
    public static boolean goToMiuiPermissionActivity_V5(Activity activity, int requestCode) {

        String packageName = activity.getPackageName();
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts(PACKAGE, packageName, null);
        intent.setData(uri);
        if (isIntentAvailable(intent, activity)) {
            activity.startActivityForResult(intent, requestCode);
            return true;
        }
        return false;
    }

    /**
     * 小米 V6 V7 版本 ROM权限申请
     */
    public static boolean goToMiuiPermissionActivity_V6(Activity activity, int requestCode) {

        Intent intent = new Intent(MIUI_INTENT_ACTION_APP_PERM_EDITOR);
        intent.setClassName(COM_MIUI_SECURITY_CENTER, COM_MIUI_PERMCENTER_PERMISSIONS_APP_PERMISSIONS_EDITOR_ACTIVITY);
        intent.putExtra(EXTRA_PACKGE_NAME, activity.getPackageName());
        if (isIntentAvailable(intent, activity)) {
            activity.startActivityForResult(intent, requestCode);
            return true;
        }
        return false;
    }

    /**
     * 小米 V8 版本 ROM权限申请
     */
    public static boolean goToMiuiPermissionActivity_V8(Activity activity, int requestCode) {

        Intent intent = new Intent(MIUI_INTENT_ACTION_APP_PERM_EDITOR);
        intent.setClassName(COM_MIUI_SECURITY_CENTER, COM_MIUI_PERMCENTER_PERMISSIONS_PERMISSIONS_EDITOR_ACTIVITY);
        intent.putExtra(EXTRA_PACKGE_NAME, activity.getPackageName());
        if (isIntentAvailable(intent, activity)) {
            activity.startActivityForResult(intent, requestCode);
            return true;
        }
        return false;
    }

    private static boolean isIntentAvailable(Intent intent, Context context) {

        if (intent == null) {
            return false;
        }
        return context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() > 0;
    }

    public static void gotoReqSystemAlertPermission(Activity activity) {

        if (mIsMiuiSystem) {
            if (gotoMiuiAlertWindowSystem(activity, OVERLAY_PERMISSION_REQ_CODE)) {
                return;
            }
        }
        gotoSystemAlertWindowSetting(activity);
    }

    public static void gotoSystemAlertWindowSetting(Activity activity) {

        String field = getStaticField(Settings.class, "ACTION_MANAGE_OVERLAY_PERMISSION", ACTION_MANAGE_OVERLAY_PERMISSION);
        Intent intent = new Intent(field, Uri.parse(PACKAGE + ":" + activity.getPackageName()));
        activity.startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
    }

    private static String getStaticField(Class cls, String fieldName, String defaultValue) {

        String result = defaultValue;
        try {
            Field field = cls.getField(fieldName);
            if (null != field) {
                Object object = field.get(null);
                if (null != object) {
                    result = String.valueOf(object);
                }
            }
        } catch (Exception e) {
            XLog.w(e.toString());
        }
        return result;
    }

    public static boolean canShowSystemAlert(Context context) {
        try {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            Method dispatchMethod = AppOpsManager.class.getMethod("checkOp", new Class[]{int.class, int.class, String.class});
            //AppOpsManager.OP_SYSTEM_ALERT_WINDOW = 24
            int mode = (Integer) dispatchMethod.invoke(manager, new Object[]{24, Binder.getCallingUid(), context.getApplicationContext().getPackageName()});
            return AppOpsManager.MODE_ALLOWED == mode;
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return context.checkSelfPermission("android.permission.SYSTEM_ALERT_WINDOW") == PackageManager.PERMISSION_GRANTED;
            }
            return true;
        }
    }
}